import { login, wxLogin, getEmailCode } from '@/api/user';
import type { TLoginReq } from '@/api/user/type';
import { ResultCodeEnum } from '@/enums';
import { useUserStore } from '@/store';
import { useToast } from 'wot-design-uni';

export const useLogin = (isAgree: Ref<boolean>) => {
  const redirect_url = ref('/pages/center/index');
  onLoad((options) => {
    console.log('打印***options', options);
    if (options && options.redirect_url) {
      redirect_url.value = decodeURIComponent(options.redirect_url);
    }
  });

  const getOpenid = (): Promise<string> => {
    // #ifdef MP-WEIXIN
    return new Promise((resolve) => {
      uni.login({
        provider: 'weixin',
        success: async (res: any) => {
          const r = await wxLogin(res.code);
          if (r.code === ResultCodeEnum.SUCCESS) {
            resolve(r.data);
          } else {
            resolve('');
          }
        }
      });
    });
    // #endif
  };

  const userStore = useUserStore();
  const { success: showSuccess, info } = useToast();

  const tab = ref(0);
  const tabList = ref([
    {
      title: '账号密码登录',
      type: 'password'
    },
    {
      title: '邮箱登录',
      type: 'email'
    }
  ]);

  const value1Label = computed(() => {
    return tabList.value[tab.value].type === 'password' ? '用户名' : '邮箱';
  });

  const value2Label = computed(() => {
    return tabList.value[tab.value].type === 'password' ? '密码' : '验证码';
  });

  const form = ref();
  const model = reactive({
    value1: '',
    value2: ''
  });

  watch(
    () => tab.value,
    () => {
      model.value1 = '';
      model.value2 = '';
    }
  );

  const codeText = computed(() => {
    if (
      !model.value1 ||
      (!isFetching.value && model.value1) ||
      (!isFetching.value && !time.value)
    )
      return '获取验证码';
    if (isFetching && time) return `${time.value / 1000}s后重新获取`;
  });
  const time = ref(0);
  const isFetching = ref(false);
  const disabled = computed(() => {
    console.log(
      '打印***!model.value1 || isFetching.value',
      !model.value1 || isFetching.value
    );
    return !model.value1 || isFetching.value;
  });

  const getCode = async () => {
    isFetching.value = true;
    time.value = 60 * 1000;
    const id = setInterval(() => {
      time.value -= 1000;
      if (time.value === 0) {
        clearInterval(id);
        isFetching.value = false;
      }
    }, 1000);
    const { code, data } = await getEmailCode(model.value1);
    if (code === ResultCodeEnum.SUCCESS) {
      showSuccess({ msg: data });
    }

    console.log('getCode');
  };

  const handleSubmit = async () => {
    const { valid } = await form.value.validate();
    if (!valid) return;
    if (!isAgree.value) return info({ msg: '请阅读并同意隐私保护指引' });

    const openid = await getOpenid();
    console.log('打印***openid', openid);

    const value1 = model.value1.trim();
    const value2 = model.value2.trim();
    const params: TLoginReq = tab.value
      ? { email: value1, code: value2, openid }
      : { name: value1, password: value2, openid };

    const { code, data } = await login(params);
    if (code === ResultCodeEnum.SUCCESS) {
      showSuccess({
        msg: '登录成功'
      });
      userStore.setUserInfo(data);
      setTimeout(() => {
        uni.switchTab({
          url: redirect_url.value,
          fail() {
            uni.navigateTo({ url: redirect_url.value });
          }
        });
      }, 500);
    }
  };

  const goRegister = () => {
    uni.navigateTo({
      url: '/pages/center/register/index'
    });
  };

  return {
    disabled,
    codeText,
    value1Label,
    value2Label,
    tab,
    tabList,
    model,
    form,
    isAgree,
    handleSubmit,
    goRegister,
    getCode
  };
};
